package com.xiaojie.springboot.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author xiaojie
 * @version 1.0
 * @description: fanout消费者
 * @date 2021/9/25 22:57
 */
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue("xiaojie_fanout_queue"),
        exchange = @Exchange(value = "xiaojie_fanout_exchange", type = ExchangeTypes.FANOUT),
        key = ""))
@Slf4j
public class FanoutMsgConsumer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @description: 接收到信息
     * @param:
     * @param: msg
     * @return: void
     * @author xiaojie
     * @date: 2021/9/25 23:02
     */
    @RabbitHandler
    public void handlerMsg(@Payload String msg, @Headers Map<String, Object> headers,
                           Channel channel) throws IOException {

        log.info("接收到的消息是fanout：{}" + msg);
        //delivery tag可以从消息头里边get出来
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
//        int i=1/0; 模拟重试机制，如果重试则代码不能try(有点类似事务)，并且自动应答模式下，重试次数结束之后，自动应答消息出队列。
        //手动应答，第二个参数为是否批量处理
        channel.basicAck(deliveryTag, false);
        boolean redelivered = (boolean) headers.get(AmqpHeaders.REDELIVERED);
        //第二个参数为是否批量，第三个参数为是否重新进入队列，如果为true，则重新进入队列
//        channel.basicNack(deliveryTag, false, !redelivered);
    }

}
